import { HttpClient } from '@angular/common/http';
import { Component, ElementRef, Inject, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { AuthService } from '@app/core/auth/auth.service';
import { CustomerConfigService } from '@app/core/public-api';
import { EntityType } from '@app/shared/public-api';

@Component({
  selector: 'tb-videos-play',
  templateUrl: './videos-play.component.html',
  styleUrls: ['./videos-play.component.scss']
})
export class VideosPlayComponent implements OnInit {
  videoUrl = "";
  videos = [];
  @ViewChildren('video')
  videorefsl: QueryList<ElementRef<HTMLVideoElement>>;
  _videosList = [];
  videosList = [];
  videocount = 4;
  constructor(private http: HttpClient, @Inject(MAT_DIALOG_DATA) public data: { vids: string[], entityType: EntityType }, private customerconfigService: CustomerConfigService) {
    console.log(this.data);
    let narr = []
    let c = this.data.vids;
    for (let i = 0; i < c.length; i += this.videocount) {
      let t1 = [];
      for (let vc = 0; vc < this.videocount; vc++) { 
        c[i+vc] && t1.push(c[i+vc]) 
      }
      narr.push(t1)
    }
    this._videosList = narr;

  }
  closevideo() {
    const flvjs = (window as any).flvjs;
  }
  activeindex = 0;
  videoControllers = [];
  playVideo(i) {
    this.videoControllers.forEach(i => {
      i.destroy()
    })
    this.videoControllers=[]
    this.activeindex = i;
    this.videosList = this._videosList[this.activeindex].map((v, i) => {
      return new Promise((res, rej) => {
         
        let orgcode=this.customerconfigService.getConfig().orgConfig.tenant.title
       
        this.http.post('/api/tenant_ip/getRtsp', { cameraId: v, minute: 0, orgcode })
          .subscribe(e => {
            let ele = (this.videorefsl as any)?._results[i].nativeElement;
            const response = e as any;
            const flvjs = (window as any).flvjs;
            let url = `/api/flv/get_flv?url=${response.result}`;
            this.videoUrl = url;
            let flvPlayer = flvjs.createPlayer({
              type: 'flv',
              url: url,
            }, {
              headers: {
                "X-Authorization": "Bearer " + AuthService.getJwtToken()
              }
            });
            flvPlayer.attachMediaElement(ele);
            flvPlayer.load()
            res({ done: true })
            this.videoControllers[i] = flvPlayer
            console.log(this.videosList)
          });
      })

    });

  }
  ngOnInit(): void {
    this.playVideo(0);
  }
  ngOnDestroy(): void {
    this.videoControllers.forEach(i => {
      i.destroy()
    })

  }

  changeVideoCount(){
  this.videocount=  this.videocount==1?4:1;
  this.videoControllers.forEach(i=>{
    i.destroy()
  })
  this.videoControllers=[]
let narr = []
let c = this.data.vids;
for (let i = 0; i < c.length; i += this.videocount) {
  let t1 = [];
  for (let vc = 0; vc < this.videocount; vc++) { 
    c[i+vc] && t1.push(c[i+vc]) 
  }
  narr.push(t1)
}
this._videosList = narr;
this.playVideo(0)
  }
}
